package com.andnnl.template.param;

import com.fasterxml.jackson.databind.JsonNode;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

/**
 * Created by chenss on 2025/7/8.
 */
// 浮点类型配置
public class DoubleParamConfig extends NumericParamConfig<Double> {
    @Override
    public void validate() {
        if (minValue != null && maxValue != null && minValue > maxValue)
            throw new IllegalArgumentException("数值范围无效: " + name);
    }

    @Override
    public String generateValue() {
        Double min = (minValue != null) ? minValue : 0.0d;
        Double max = (maxValue != null) ? maxValue : 100.0d;
        return String.valueOf(RandomUtil.randomDouble(min, max));
    }

    @Override
    public void fromJson(JsonNode node) {
        if (node.has("minValue") && !node.get("minValue").isNull()) {
            setMinValue(node.get("minValue").asDouble());
        }
        if (node.has("maxValue") && !node.get("maxValue").isNull()) {
            setMaxValue(node.get("maxValue").asDouble());
        }
    }

    @Override
    public boolean validateValue(String value) throws IllegalArgumentException {
        if (StrUtil.isBlank(value)) {
            throw new IllegalArgumentException("浮点参数" + name + "不能为空");
        }
        try {
            double doubleValue = Double.parseDouble(value);
            if (minValue != null && doubleValue < minValue) {
                throw new IllegalArgumentException("浮点参数" + name + "必须大于等于" + minValue + "，实际值：" + doubleValue);
            }
            if (maxValue != null && doubleValue > maxValue) {
                throw new IllegalArgumentException("浮点参数" + name + "必须小于等于" + maxValue + "，实际值：" + doubleValue);
            }
            return true;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("参数" + name + "不是有效的浮点数: " + value, e);
        }
    }
}
